package engine.filesystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import common.Log;


/**
 * FileScanner
 * 
 * Scans a given directory for files. If not found, it then scans a defined zip
 * file for the entry.
 **/
public class FileScanner {
	public FileScanner(String zipFile, String overloadPath) {
		ZipFileName = zipFile;
		OverloadPath = overloadPath;
		loadZipFile();
	}
	
	public final String ZipFileName;
	public final String OverloadPath;
	private ZipFile _Zip;
	
	private boolean loadZipFile() {
		try {
			_Zip = new ZipFile(ZipFileName);
		} catch (IOException e) {
			Log.error("Unable to load " + ZipFileName);
			_Zip = null;
			return false;
		}
		return true;
	}
	
	
	public InputStream openFile(String name) {
		String path = OverloadPath + name;
		FileInputStream fileStream;
		File file = new File(path);
		
		// Try to overload it from the file system.
		if(file.exists()) {
			try {
				fileStream = new FileInputStream(file);
				return fileStream;
			} catch (FileNotFoundException e) {
				Log.error("Error overloading file " + name + " using " + ZipFileName + " instead.");
			}
		}
		
		// Check the zipfile.
		if(_Zip == null) {
			return null;
		}
		InputStream stream;
		ZipEntry entry = _Zip.getEntry(name);
		if(entry == null) {
			Log.error("File not found " + name + " in " + ZipFileName + ".");
			return null;
		}
		try {
			stream = _Zip.getInputStream(entry);
		} catch (IOException e) {
			Log.error("Error loading " + name + " in " + ZipFileName + ".");
			return null;
		}
		return stream;
	}
}